package com.nhjf.common.util;



import com.nhjf.common.util.ssl.HttpsClientUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class FileHelper {
	/**
	 * �����༶Ŀ¼
	 */
	public static boolean creatDirs(String dir) {
		File aFile = new File(dir);
		if (!aFile.exists()) {
			return aFile.mkdirs();
		} else {
			return true;
		}
	}
	
	/**
	 * 根据url生成html文件
	 * 
	 * 若文件存在，则替换内容
	 * 
	 * @param url
	 *            请求地址
	 * @param path
	 *            生成文件路径
	 * @return
	 */
	public static boolean requestHtmlToFile(URL url, String path) {
		try {
			URLConnection uc = url.openConnection();
			InputStream is = uc.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String content = null;
			StringBuffer html = new StringBuffer();
			while ((content = reader.readLine()) != null) {
				html.append(content+"\n");
			}
			is.close();
			File f = new File(path);
			BufferedWriter writer = new BufferedWriter(new FileWriter(f, false));
			String str = new String(html.toString());  ;
			writer.write(str);
			writer.close();
			return true;
		} catch (Exception e) {
			 e.printStackTrace();
			return false;
		}
	}
	
	
	/**
	 * 根据url生成html文件
	 * 
	 * 若文件存在，则替换内容
	 * 
	 * @param url
	 *            请求地址
	 * @param path
	 *            生成文件路径
	 * @return
	 */
	public static boolean urlToFile(String url, String path) {
		try {
			path = path.replaceAll("file:","");

			URL realUrl = new URL(url);
			String html = "";
			if (realUrl.getProtocol().toLowerCase().equals("https")) {
				HttpResponse httpResponse = HttpsClientUtil.reqForGet(url,null);
				if (1 == httpResponse.getResponseState()){
					html = httpResponse.getResult();
				}
			}else {
				html=HttpClientUtil.send(url, null, "utf-8");
			}
			File f = new File(path);
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(path, false),"UTF-8");
            BufferedWriter writer = new BufferedWriter(osw);
			String str = new String(html.toString());
			writer.write(str);
			writer.close();
			return true;
		} catch (Exception e) {
			 e.printStackTrace();
			return false;
		}
	}
	
}
